package edu.jxut.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.jxut.reggie.common.R;
import edu.jxut.reggie.pojos.Category;
import edu.jxut.reggie.server.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService;
    @GetMapping("page")
    public R<Page> selectByPage(@RequestParam("page") Integer page
                                ,@RequestParam("pageSize") Integer pageSize){

        Page<Category> byPage=categoryService.queryByPage(page,pageSize);

        return R.success(byPage);
    }

    @PostMapping
    public R<String> saveCategory(@RequestBody Category category){
        log.info("category{}",category);
        categoryService.save(category);
        return R.success("保存成功");
    }

    @DeleteMapping
    public R<String> deleteCategory(@RequestParam("id") Long id){
        log.info("删除id为{}",id);
        categoryService.removeById(id);
        return R.success("删除成功!");
    }

    @PutMapping
    public R<String> updateCategory(@RequestBody Category category){
        log.info("修改category为：{}",category);
        categoryService.updateById(category);
        return R.success("修改成功！");
    }

    @GetMapping("{id}")
    public R<Category> findOneById(@PathVariable long id){
        Category byId = categoryService.getById(id);
        return R.success(byId);
    }

    @GetMapping("/list")
    public R<List> findByType(@RequestParam(value = "type",required = false) Integer type){
        if (type==null){
            List<Category> list = categoryService.list();
            return R.success(list);
        }

        List<Category> list = categoryService.list(new LambdaQueryWrapper<Category>().eq(Category::getType, type));
        return R.success(list);
    }

}
